package com.mbyte.easy.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mbyte.easy.admin.entity.Allot;
import com.mbyte.easy.admin.entity.Check;
import com.mbyte.easy.admin.entity.Draft;
import com.mbyte.easy.admin.entity.Group;
import com.mbyte.easy.admin.service.*;
import com.mbyte.easy.common.constant.*;
import com.mbyte.easy.common.controller.BaseController;
import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.util.PageInfo;
import com.mbyte.easy.util.Utility;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassNameDraftCheckerController
 * @Description 稿件校对人校对
 * @Author myr
 * @Date 2019/12/11 15:30
 * @Version 1.0
 **/
@Slf4j
@Controller
@RequestMapping("/draft/draftChecker")
public class DraftCheckerController extends BaseController{

    private String prefix = "admin/draft/draftCheck/";

    @Autowired
    private ICheckService checkService;
    @Autowired
    private IDraftService draftService;
    @Autowired
    private IAllotService allotService;
    @Autowired
    private IGroupService groupService;
    @Autowired
    private IPptService pptService;

    @RequestMapping
    public String index(Model model,
                        @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,String createTimeSpace,
                        @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,
                        Draft draft) {
        IPage<Draft> pageInfo = draftService.draftCheckerIndex(pageNo,pageSize,draft,createTimeSpace);
        Page<Draft> page = new Page<>(pageNo,pageSize);

        log.info("getStatusCode==="+draft.getStatusCode());
        //组号回显处理========
        QueryWrapper<Draft> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("status_code",draft.getStatusCode());
        queryWrapper.groupBy("group_id");
        queryWrapper.lambda().orderByDesc(Draft::getCreateTime);
        //登录人user_id与t_group表的userId所对应。
        QueryWrapper<Group> groupQueryWrapper=new QueryWrapper<>();
        groupQueryWrapper=groupQueryWrapper.eq("user_id",draftService.getUserIdByUserName(Utility.getCurrentUsername()).getId());
        //获取当前登录人的groupList
        List<Group> groupList = groupService.list(groupQueryWrapper);
        List<String> groupIds = new ArrayList<>(groupList.size());
        if (!org.springframework.util.CollectionUtils.isEmpty(groupList)) {
            //获取GroupList的group_id字段
            for (int i = 0; i < groupList.size(); i++) {
                groupIds.add(groupList.get(i).getGroupId());
            }
            queryWrapper = queryWrapper.in("group_id", groupIds);
        }
        List<Draft> drafts = draftService.list(queryWrapper);

        if (drafts!=null){
            for (Draft draft1 : drafts) {
                for (Group group : groupList) {
                    if(draft1.getGroupId().equals(group.getGroupId())){
                        draft1.setGroupName(group.getName());//
                    }
                }
            }
            model.addAttribute("drafts", drafts);
        }else{
            model.addAttribute("drafts", 0);
        }

        QueryWrapper<Draft> draftQueryWrapper = new QueryWrapper<>();
        if(!ObjectUtils.isEmpty(draft.getGroupId())){
            draftQueryWrapper = draftQueryWrapper.eq("group_id",draft.getGroupId());
        }else {
            if(!org.springframework.util.CollectionUtils.isEmpty(groupIds)){
                draftQueryWrapper.in("group_id",groupIds);
            }
        }
        List<Draft> draftList = draftService.list(draftQueryWrapper);
        if (draftList != null && draftService.selectRoleId() == SysRole.Draft_Checker) {
                Integer draftListSize =  draftService.getNeedCheckSize(draft.getGroupId()
                        ,false,StatusWriter.STATUS_WRRITE_ARTICLEREADERLEADER_SUCCESS
                        ,StatusWriter.STATUS_WRRITE_ARTICLEFINALLEADER_SUCCESS
                        ,StatusWriter.STATUS_WRRITE_ARTICLEREADER_SUCCESS);
                model.addAttribute("draftListSize",draftListSize);
            }else if (draftList != null && draftService.selectRoleId() == SysRole.SEVEN_PROOFREADER){
            log.info("sql开始处");
                Integer draftListSize =  draftService.getNeedCheckSize(draft.getGroupId()
                        ,false,StatusWriter.STATUS_WRRITE_ARTICLEREADERLEADER_SEVEN_SUCCESS
                        ,StatusWriter.STATUS_WRRITE_ARTICLEFINALLEADER_SUCCESS
                        ,StatusWriter.STATUS_WRRITE_ARTICLEFINALLEADER_SEVEN_SUCCESS);
                model.addAttribute("draftListSize",draftListSize);
            }else {
            model.addAttribute("draftListSize", 0);
        }
        if ( ObjectUtils.isEmpty(draft.getGroupId()) || draft.getGroupId().length() < 20){
            QueryWrapper<Draft> draftQueryWrapper1=new QueryWrapper<>();
            draftQueryWrapper1.eq("status_code",StatusWriter.ERROR);
            IPage<Draft> pageInfo1 = draftService.page(page, draftQueryWrapper1);
            model.addAttribute("searchInfo", draft);
            model.addAttribute("pageInfo", new PageInfo(pageInfo1));
            return prefix + "checker-draft";
        }

        model.addAttribute("time",createTimeSpace); //时间回显
        model.addAttribute("searchInfo", draft);//查询条件前端回显
        model.addAttribute("pageInfo", new PageInfo(pageInfo));//分页数据
        model.addAttribute("draftTypes",draftService.setDraftType());//稿件类型回显
        model.addAttribute("draftCheckStatus",draftService.setDraftCheckStatus());//稿件审核状态回显
        model.addAttribute("stateDic", StateDic.stateDic());
        showReason(model,draft);
        return prefix+"checker-draft";
    }


    private void showReason(Model model,Draft draft){
        List<Check> checkList = checkService.list(new QueryWrapper<Check>().lambda()
                .eq(Check::getDraftId,draft.getId())
                .eq(Check::getUserId,draft.getLastOperator())
                .orderByDesc(Check::getCreateTime));
        String reason = null;
        if(!CollectionUtils.isEmpty(checkList)){
            reason = checkList.get(0).getReason();
        }
        model.addAttribute("reason",reason);
    }

    /**
     * @Description 稿件校对人审核通过
     * @param draftId
     * @Author myr
     * @return
     **/
    @PostMapping("check")
    @ResponseBody
    public AjaxResult check(String draftId ,Draft draftPre){
        log.info("the draftid is --> {}",draftId);
        return toAjax(draftService.passUtil(Long.valueOf(draftId),draftPre));
    }
    /**
     * @Description //稿件校对人审核通过 / 拒绝 / 被驳回
     * @Author 张雪
     * @return
     **/
    @RequestMapping("checkerSuccess")
    public String checkerSuccess(Model model,Draft draft,
                                 @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,String createTimeSpace,
                                 @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize) {
        Page<Draft> page = new Page<>(pageNo, pageSize);
        //分配表被分配人为自己
        QueryWrapper<Draft> draftQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Allot> allotQueryWrapper = new QueryWrapper<>();
        allotQueryWrapper.eq("allotNo_id",pptService.selectIdByUsername(Utility.getCurrentUsername()));
        List<Allot> allotList = allotService.list(allotQueryWrapper);
        List draftIds = new ArrayList();
        for (Allot allot:allotList){
            draftIds.add(allot.getDraftId());
        }
        if(draftIds.size()!=0) {
            draftQueryWrapper.in("id", draftIds);
        }
        if (!ObjectUtils.isEmpty(createTimeSpace)) {
            String begin = createTimeSpace.substring(0, 19);
            String end = createTimeSpace.substring(22);
            draftQueryWrapper.lambda().between(Draft::getSubmitTime, begin, end);
        }

        if (!ObjectUtils.isEmpty(draft.getSubmitTime())) {
            draftQueryWrapper = draftQueryWrapper.like("submit_time", draft.getSubmitTime());
        }
        if (!ObjectUtils.isEmpty(draft.getDraftTitle())) {
            draftQueryWrapper = draftQueryWrapper.like("draft_title", draft.getDraftTitle());
        }

        if (!ObjectUtils.isEmpty(draft.getDraftType()) && draft.getDraftType() >= DraftType.Image_Text) {
            draftQueryWrapper = draftQueryWrapper.like("draft_type", draft.getDraftType());
        }
        if (!ObjectUtils.isEmpty(draft.getIsPass())) {
            draftQueryWrapper = draftQueryWrapper.eq("is_pass", draft.getIsPass());
        }
        log.info("status_code="+draft.getStatusCode());
        draftQueryWrapper.eq("status_code",draft.getStatusCode());
        draftQueryWrapper.lambda().orderByDesc(Draft::getUpdateTime);
        //组名回显
        Map<String,String> groupIDList = new HashMap<>();
        List<Draft> drafts = draftService.list(draftQueryWrapper);
        for (Draft draft1:drafts) {
            groupIDList.put(draft1.getGroupId(),groupService.getNameByGroupId(draft1.getGroupId()));
        }
        model.addAttribute("groupIDList",groupIDList);
        setDraftType(model);
        setDraftCheckStatus(model);
        model.addAttribute("draftTypes",draftService.setDraftType());
        model.addAttribute("time", createTimeSpace);
        IPage<Draft> pageInfo = draftService.page(page, draftQueryWrapper);
        model.addAttribute("stateDic", StateDic.stateDic());
        model.addAttribute("searchInfo", draft);
        model.addAttribute("pageInfo", new PageInfo(pageInfo));
        return prefix + "checker";
    }
    /**
     * 稿件类型数据回显
     * @param model
     */
    public void setDraftType(Model model){
        Map<Integer,String> types = new HashMap<Integer,String>();
        types.put(DraftType.Image_Text,"图文");
        types.put(DraftType.QA,"问答");
        types.put(DraftType.PPT,"PPT");
        types.put(DraftType.Audio,"音频");
        model.addAttribute("draftTypes",types);
    }

    /**
     * 稿件审核状态回显
     * @param model
     */
    public void setDraftCheckStatus(Model model){
        Map<Integer,String> status = new HashMap<Integer,String>();

        status.put(DraftIsPass.Pass,"已通过");
        status.put(DraftIsPass.NotPass,"未通过");
        status.put(DraftIsPass.NotCheck,"未审核");
        model.addAttribute("draftCheckStatus",status);
    }


}
